# udp_gb_client.py
"""UDP 广播接收工具

监听并接收局域网内的 UDP 广播消息，用于设备发现和网络测试。

:用法:
    .. code-block:: bash

        python whoAreaYou.py

:功能:
    * 创建 UDP 广播接收套接字
    * 监听指定端口的广播消息
    * 显示发送方地址和消息内容

:示例:
    .. code-block:: bash

        > python whoAreaYou.py
        Listening for broadcast at ('0.0.0.0', 1060)
        Server received from ('192.168.1.100', 51234): hello is me!

:配置:
    * 监听端口: 1060
    * 监听地址: 所有可用地址 (0.0.0.0)
    * 缓冲大小: 65535 字节

:注意:
    * 需要配合发送端 whereAmI.py 使用
    * 确保网络允许 UDP 广播
    * 防火墙可能需要放行端口
    * 使用 Ctrl+C 终止程序
"""

import socket
import sys

def receive_broadcast(port=1060):
    """监听并接收 UDP 广播消息。

    :param port: 监听端口号，默认为 1060
    :type port: int
    :returns: 接收成功返回 True，失败返回 False
    :rtype: bool
    :raises socket.error: 当套接字操作失败时
    
    :示例:

    .. code-block:: python

        success = receive_broadcast(1060)
        if success:
            print("接收完成")
    """
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
            s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            s.bind(('', port))
            print('Listening for broadcast at', s.getsockname())

            while True:
                try:
                    data, address = s.recvfrom(65535)
                    print('Server received from {}:{}'.format(
                        address, data.decode('utf-8')))
                except KeyboardInterrupt:
                    print("\n接收终止")
                    break
                except Exception as e:
                    print(f"接收数据时出错: {e}")

    except socket.error as e:
        print(f"创建套接字时出错: {e}")
        return False
    except Exception as e:
        print(f"发生未知错误: {e}")
        return False
    return True

if __name__ == "__main__":
    success = receive_broadcast()
    sys.exit(0 if success else 1)